<?php
// +----------------------------------------------------------------------
// | astp [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 获取用户授权信息回调
// +----------------------------------------------------------------------
namespace app\wechat\controller;

use EasyWeChat\Foundation\Application;
use think\facade\Session;
use think\facade\Config;
use think\Controller;
use think\Db;

class UserAuth extends Controller
{
  // 授权回调
  public function oauth_callback()
  {
    $options = Config::get('wewhat.wxConfig');
    $app = new Application($options);
    $oauth = $app->oauth;
    // 获取 OAuth 授权结果用户信息
    $user = $oauth->user();
    // 更新写入数据库
    $wechat_user = $user->getOriginal();
    $info = Db::name('user')->where('openid','=',$wechat_user['openid'])->find();
    $post = [];
    $post['nickname'] = $wechat_user['nickname'];
    $post['sex'] = $wechat_user['sex'];
    $post['headimgurl'] = $wechat_user['headimgurl'];
    $post['openid'] = $wechat_user['openid'];
    if( $info ) {
      Db::name('user')->where('openid','=',$wechat_user['openid'])->update($post);
    } else {
      Db::name('user')->insert($post);
    }
    Session::set('wechat_user',$user->getOriginal());
    $targetUrl = empty(Session::get('target_url')) ? '/' : Session::get('target_url');
    $this->redirect($targetUrl);
  }

}
?>